package urban_elements

import (
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/model/system/system_districts"
	"gitee.com/theegg/go-brick/app/model/system/system_images"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/chtml"
	"gitee.com/theegg/go-brick/app/service/help/cslice"
	"strings"
)

// 查询参数
type QueryParams struct {
	PageSize   string `form:"page_size"  binding:"gte=0,lte=100" label:"每页数量"`
	PageIndex  string `form:"page_index"  binding:"gte=0,lte=99999" label:"当前页数"`
	Country    string `form:"country"  binding:"" label:"国家"`
	Title      string `form:"title"  binding:"omitempty,customPlainText=4 32" label:"标题"`
	TypeId     int    `form:"type_id"  binding:"" label:"类型"`
	TypeSubId  int    `form:"type_sub_id"  binding:"" label:"子类型"`
	ProvinceId int64  `form:"province_id"  binding:"" label:"省份"`
	CityId     int64  `form:"city_id"  binding:"" label:"城市"`
}

// 添加参数
type AddParams struct {
	Id        int64  `form:"id" binding:"" label:"ID"`
	TypeId    int    `form:"type_id"  binding:"required" label:"分类"`
	TypeSubId int    `form:"type_sub_id"  binding:"required" label:"子分类"`
	Title     string `form:"title"  binding:"required,customPlainText=6 64" label:"中文标题"`
	TitleEN   string `form:"title_en"  binding:"required,customPlainText=6 64" label:"英文标题"`

	Content string `form:"content"  binding:"required,customPlainText=2 1024" label:"描述"`
	// Summary  	 	string 		`form:"summary"  binding:"required,customPlainText=2 64" label:"摘要"`

	ProvinceId int64  `form:"province_id"  binding:"required,gte=1,lte=99999999" label:"省份ID"`
	CityId     int64  `form:"city_id"  binding:"required,gte=1,lte=99999999" label:"城市ID"`
	Address    string `form:"address"  binding:"required,customPlainText=6 128" label:"地址"`
	Phone      string `form:"phone"  binding:"customPhone" label:"电话"`
	Website    string `form:"website"  binding:"omitempty,url" label:"官网"`

	OpenTime     string `form:"open_time"  binding:"required,customDateTime=hh:ii" label:"开始时间"`
	CloseTime    string `form:"close_time"  binding:"required,customDateTime=hh:ii" label:"结束时间"`
	FeeTicketHas bool   `form:"fee_ticket_has"  binding:"" label:"门票"`
	FeeInnerHas  bool   `form:"fee_inner_has"  binding:"" label:"内部收费"`
	FeeAmount    string `form:"fee_amount"  binding:"customPlainText=2 64" label:"图像列表"`

	CoordinateX string `form:"coordinate_x"  binding:"required,customPlainText=6 32" label:"经度"`
	CoordinateY string `form:"coordinate_y"  binding:"required,customPlainText=6 32" label:"维度"`
	PlusCode    string `form:"plus_code"  binding:"required,customPlainText=6 64" label:"谷歌地图码"`

	Tags string `form:"tags"  binding:"required" label:"标签"`

	ImageCover string `form:"image_cover"  binding:"customUploadImage=tour/cover" label:"封面图片"`
	ImageList  string `form:"image_list"  binding:"customUploadImage=tour/content m" label:"图片集合"`
}

// 分页获取所有数据
// @param params map 参数
// @return interface{}, error
func GetDataList(params map[string]interface{}) (map[string]interface{}, error) {
	returnData := make(map[string]interface{}, 0)

	queryParams, errBuild := model.BuildAdminQueryParam(params)
	if errBuild != nil {
		return nil, app.NewError(errBuild)
	}

	query := app.Db().Desc("id").Limit(queryParams.Limit, queryParams.Offset)

	// query province_id
	if _, ok := queryParams.Params["province_id"]; ok && queryParams.Params["province_id"].(int64) > 0 {
		query.Where("province_id = ?", queryParams.Params["province_id"])
	}

	// query city id
	if _, ok := queryParams.Params["city_id"]; ok && queryParams.Params["city_id"].(int64) > 0 {
		query.Where("city_id = ?", queryParams.Params["city_id"])
	}

	// query type_sub_id
	if _, ok := queryParams.Params["type_sub_id"]; ok && queryParams.Params["type_sub_id"].(int) > 0 {
		query.Where("type_sub_id = ?", queryParams.Params["type_sub_id"])
	}

	// query type_id
	if _, ok := queryParams.Params["type_id"]; ok && queryParams.Params["type_id"].(int) > 0 {
		query.Where("type_id = ?", queryParams.Params["type_id"])
	}

	// query title
	if _, ok := queryParams.Params["title"]; ok && queryParams.Params["title"] != "" {
		query.Where("title like ?", "%"+queryParams.Params["title"].(string)+"%")
	}

	// query country
	if _, ok := queryParams.Params["country"]; ok && queryParams.Params["country"].(string) != "" {
		query.Where("country = ?", queryParams.Params["country"])
	}

	data := make([]UrbanElements, 0)
	// 求总条数
	total, err := query.FindAndCount(&data)
	if err != nil {
		return nil, app.NewError(err)
	}

	for i, v := range data {
		data[i].ProvinceTitle = system_districts.GetDistrictName(v.ProvinceId)
		data[i].CityTitle = system_districts.GetDistrictName(v.CityId)

		name, errTypeName := GetTypeName(v.TypeId, v.TypeSubId)
		if errTypeName != nil {
			return nil, app.NewError(errTypeName)
		}

		data[i].TypeSubTitle = name

		data[i].ImageCoverUrl = app.GetImageStaticUrl(data[i].ImageCover)

		imageList := strings.Split(v.ImageList, ",")
		imageListArr := make([]map[string]interface{}, 0)
		for ii, vv := range imageList {
			if vv != "" {
				imageListArr = append(imageListArr, map[string]interface{}{
					"id":         ii,
					"image_name": vv,
					"url":        app.GetImageStaticUrl(vv),
				})
			}
		}

		data[i].ImageListArr = imageListArr
	}

	returnData["data"] = data
	returnData["total"] = total

	return returnData, nil
}

// @title AddOrUpdate
// @description 更新或者添加
func (te *UrbanElements) AddOrUpdate(params AddParams) error {

	if !IsHasMainType(params.TypeId) {
		return app.NewError("不存在的主类型")
	}

	if !IsHasSubType(params.TypeId, params.TypeSubId) {
		return app.NewError("不存在的类型")
	}

	if !system_districts.IsHasProvince(params.ProvinceId) {
		return app.NewError("不存在的省份")
	}

	if !system_districts.IsHasCity(params.ProvinceId, params.CityId) {
		return app.NewError("不存在的城市")
	}

	imageChangeList := map[string][]string{
		"add": make([]string, 0),
		"del": make([]string, 0),
	}

	// 1. 图片集合拆解
	imageList := make([]string, 0)
	for _, v := range strings.Split(params.ImageList, ",") {
		if v != "" {
			imageList = append(imageList, v)
		}
	}

	// 2. 整理图片变更
	if te.Id > 0 {
		if te.ImageList != "" {
			imageOldList := strings.Split(te.ImageList, ",")
			if len(imageOldList) > 0 {
				imageChangeList["del"] = append(imageChangeList["del"], cslice.StringSliceMainDiff(imageOldList, imageList)...)
			}
		}

		if te.ImageCover != params.ImageCover {
			imageChangeList["add"] = append(imageChangeList["add"], params.ImageCover)
			if te.ImageCover != "" {
				imageChangeList["del"] = append(imageChangeList["del"], te.ImageCover)
			}
		}
	} else {
		imageChangeList["add"] = imageList
		if params.ImageCover != "" {
			imageChangeList["add"] = append(imageChangeList["add"], params.ImageCover)
		}
	}

	te.PartnerSign = "default"
	te.TypeId = params.TypeId
	te.TypeSubId = params.TypeSubId

	te.Title = chtml.HtmlPlainText(params.Title)
	te.TitleEn = chtml.HtmlPlainText(params.TitleEN)

	te.Content = chtml.HtmlPlainText(params.Content)
	te.Tags = chtml.HtmlPlainText(params.Tags)

	te.ProvinceId = params.ProvinceId
	te.CityId = params.CityId
	te.Address = params.Address

	te.OpenTime = params.OpenTime
	te.CloseTime = params.CloseTime

	te.Phone = params.Phone
	te.Website = params.Website

	te.FeeTicketHas = params.FeeTicketHas
	te.FeeInnerHas = params.FeeInnerHas
	te.FeeAmount = params.FeeAmount

	te.CoordinateX = params.CoordinateX
	te.CoordinateY = params.CoordinateY
	te.PlusCode = params.PlusCode

	te.ImageCover = params.ImageCover
	te.ImageList = params.ImageList

	// 3. 开启事务 插入数据
	session := app.Db().NewSession()
	defer session.Close()
	if errSession := session.Begin(); errSession != nil {
		return app.NewError(errSession)
	}

	if te != nil && te.Id > 0 {
		affected, errUpdate := session.ID(te.Id).Update(te)

		if errUpdate != nil {
			session.Rollback()
			return app.NewError(errUpdate)
		}

		if affected != 1 {
			session.Rollback()
			return app.NewError("更新错误")
		}
	} else {

		affected, errInsert := session.Insert(te)
		if errInsert != nil {
			session.Rollback()
			return app.NewError(errInsert)
		}

		if affected != 1 {
			session.Rollback()
			return app.NewError("新增内容分类错误(0x001)")
		}
	}

	// 图片处理
	errImage := system_images.ProcessItemImage(te.Id, imageChangeList)
	if errImage != nil {
		session.Rollback()
		return app.NewError(errImage)
	}

	// 提交
	errCommit := session.Commit()
	if errCommit != nil {
		return app.NewError(errCommit)
	}

	return nil
}

// @title ModifyStatus
// @description 修改管理员状态
func (te *UrbanElements) ModifyStatus() error {
	if te.Status == -1 {
		return app.NewError("对不起, 当前内容已经被删除!")
	}

	status := 1
	if te.Status == 1 {
		status = 0
	}

	affected, err := app.Db().Table(new(UrbanElements)).ID(te.Id).Cols("status").Update(map[string]int{"status": status})

	if err != nil {
		return app.NewError(err)
	}

	// 生效条数
	if affected == 0 {
		return app.NewError("对不起, 指定的ID更新数量不正确")
	}

	return nil
}

// @title Hot
// @description Hot
func (te *UrbanElements) Hot() error {

	var nowHot bool
	if te.IsHot {
		nowHot = false
	} else {
		nowHot = true
	}

	affected, errUpdate := app.Db().Table(new(UrbanElements)).ID(te.Id).Cols("is_hot").Update(map[string]interface{}{"is_hot": nowHot})

	if errUpdate != nil {
		return app.NewError(errUpdate)
	}

	if affected != 1 {
		return app.NewError("更新错误")
	}

	return nil
}

// @title Recommend
// @description Recommend
func (te *UrbanElements) Recommend() error {

	var nowStatus bool
	if te.IsRecommend {
		nowStatus = false
	} else {
		nowStatus = true
	}

	affected, errUpdate := app.Db().Table(new(UrbanElements)).ID(te.Id).Cols("is_recommend").Update(map[string]interface{}{"is_recommend": nowStatus})

	if errUpdate != nil {
		return app.NewError(errUpdate)
	}

	if affected != 1 {
		return app.NewError("更新错误")
	}

	return nil
}

// 获取单个数据
// @param id int64 数据的id
// @return *Goods, error
func GetItemById(id int64) (*UrbanElements, error) {
	item := new(UrbanElements)
	has, err := app.Db().Where("id = ?", id).Get(item)

	if err != nil {
		return nil, err
	}

	if !has {
		return nil, app.NewError("对不起, 目标对象不存在")
	}

	return item, nil
}
